import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Row,
  Col,
  Input,
  Button,
  Divider,
  Drawer,
  Select,
  Popconfirm,
  Spin,
  Modal,
  message,
} from 'antd';
import { connect } from 'dva';
import { useAntdTable } from '@umijs/hooks';
import SlickTable from '@/components/SlickTable';
import { getPageSizeByCardHeight } from '@/utils/utils';
import request from '@/utils/request';
import Operpage from './components/Operpage';
import Deal from './components/Deal';

const { Option } = Select;

const namespace = 'abnormalOrder';

function AbnormalOrder({ size: { height }, form, dispatch }) {
  const { getFieldDecorator } = form;
  const [loading, setLoading] = useState(false);
  const [selectedRows, setSelectedRows] = useState([]);
  const [size, setSize] = useState(getPageSizeByCardHeight(height - 64 - 8));
  const [paramsObj, setParamsObj] = useState({});
  // 右抽屉显示隐藏控制
  const [visible, setVisible] = useState(false);
  // 处理模态框显示隐藏
  const [dealvisible, setDealvisible] = useState(false);

  // 通过dva存当前需要传递的数据
  // const savePassData = params => {
  //   dispatch({
  //     type: `${namespace}/savePassData`,
  //     payload: params,
  //   });
  // };
  const [sourceFromMap, setSourceFrom] = useState([]);
  const [exceptionTypeMap, setExceptionType] = useState([]);
  const [exceptionStatusMap, setExceptionStatus] = useState([]);
  useEffect(() => {
    request('pmc/pms/StaticDataController/getStaticAttr.do', {
      data: {
        busiObjNbr: 'OrderExceptionModel',
        attrNbr: 'orderFrom',
      },
    }).then(res => {
      setSourceFrom(res);
    });
    request('pmc/pms/StaticDataController/getStaticAttr.do', {
      data: {
        busiObjNbr: 'OrderExceptionModel',
        attrNbr: 'exceptionType',
      },
    })
      .then(res => {
        setExceptionType(res);
      })
      .always(() => setLoading(false));
    request('pmc/pms/StaticDataController/getStaticAttr.do', {
      data: {
        busiObjNbr: 'OrderExceptionInst',
        attrNbr: 'exceptionStatus',
      },
    })
      .then(res => {
        setExceptionStatus(res);
      })
      .always(() => setLoading(false));
  }, []);

  const getTableData = ({ current, pageSize, paramsObj }) => {
    return request('pmc/pms/ExceptionInstController/queryPage', {
      data: {
        pageNum: current,
        pageSize: pageSize,
        sortName: '',
        // sortOrder: 'asc',
        ...paramsObj,
      },
    }).then(res => {
      if (Array.isArray(res.data.records)) {
        return {
          total: res.data.total,
          data: res.data.records.map(val => {
            const { children, ...rest } = val;
            return rest;
          }),
        };
      }
      return {
        total: 0,
        data: [],
      };
    });
  };

  const { tableProps, refresh } = useAntdTable(
    params => {
      return getTableData({ ...params, pageSize: size, paramsObj });
    },
    [paramsObj, height],
    {
      defaultPageSize: size,
      form,
    }
  );
  const { pagination, ...restTableProps } = tableProps;

  useEffect(() => {
    setSize(getPageSizeByCardHeight(height - 64 - 8));
  }, [height]);

  const submit = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      // console.log(fieldsValue);
      setParamsObj({
        ...fieldsValue,
      });
    });
  };

  const handleSelectRows = value => {
    setSelectedRows(value);
  };

  const handleDeal = () => {
    setDealvisible(true);
  };

  const onClose = () => {
    setVisible(false);
  };

  const dealClose = () => {
    setDealvisible(false);
  };

  const handleBatch = () => {
    let arr = [];
    selectedRows.map(item => {
      arr.push(item.exceptionInstId);
    });
    request('pmc/pms/ExceptionInstController/handleException', { exceptionInstIdArr: arr }).then(
      res => {
        if (res) {
          refresh();
          message.success('处理成功！');
        } else {
          message.error('处理失败！');
        }
      }
    );
  };

  const handleReset = () => {
    form.resetFields();
  };

  const onConfirm = value => {
    console.log(value);
    setDealvisible(false);
  };

  const handleDealOrder = record => {
    Modal.confirm({
      content: '确定要处理该条异常工单吗?',
      onOk() {
        let arr = [];
        arr.push(record.exceptionInstId);
        request('pmc/pms/ExceptionInstController/handleException', {
          data: { exceptionInstIdArr: arr },
          method: 'POST',
        }).then(res => {
          if (res) {
            refresh();
            message.success('处理成功！');
          } else {
            message.error('处理失败！');
          }
        });
      },
    });
  };

  // 通过dva存当前需要传递的数据
  const savePassData = params => {
    dispatch({
      type: `${namespace}/savePassData`,
      payload: params,
    });
  };

  const handleOper = record => {
    setVisible(true);
    savePassData(record);
  };

  const columns = [
    {
      title: '流程实例标识',
      width: 100,
      dataIndex: 'flowInstId',
      ellipsis: true,
    },
    {
      title: '系统来源',
      width: 90,
      dataIndex: 'sourceFromName',
      ellipsis: true,
    },
    {
      title: '异常分类',
      width: 90,
      dataIndex: 'exceptionTypeName',
      ellipsis: true,
    },
    {
      title: '异常编码',
      width: 180,
      dataIndex: 'exceptionCode',
      ellipsis: true,
    },
    {
      title: '异常名称',
      dataIndex: 'exceptionModelName',
      ellipsis: true,
    },
    {
      title: '异常处理状态',
      dataIndex: 'exceptionStatusName',
      ellipsis: true,
      width: 120,
    },
    {
      title: '异常单创建时间',
      dataIndex: 'createDateStr',
      width: 150,
      // align: 'center',
      // render(text) {
      //   return <div>{selfformat(new Date(text))}</div>;
      // },
    },
    {
      title: '解决方案',
      dataIndex: 'planName',
      width: 150,
    },
    {
      title: '操作',
      width: 150,
      align: 'center',
      render: (text, record) => {
        if (record.exceptionStatus === 10) {
          return (
            <span>
              <a
                onClick={() => {
                  handleOper(record);
                }}
              >
                详情
              </a>
              <Divider type="vertical" />
              <a
                onClick={() => {
                  handleDealOrder(record);
                }}
              >
                处理
              </a>
              <Divider type="vertical" />
              <a
                onClick={() => {
                  handleEffect(record);
                }}
              >
                废弃
              </a>
            </span>
          );
        } else {
          return (
            <span>
              <a
                onClick={() => {
                  handleOper(record);
                }}
              >
                详情
              </a>
            </span>
          );
        }
      },
    },
  ];

  const handleEffect = record => {
    Modal.confirm({
      content: '确定要废弃该异常工单吗?',
      onOk() {
        request('pmc/pms/ExceptionInstController/modifyExceptionStatus', {
          data: { exceptionInstId: record.exceptionInstId, exceptionStatus: 40 },
          method: 'POST',
        }).then(res => {
          if (res) {
            refresh();
          } else {
            message.error('废弃失败！');
          }
        });
      },
    });
  };

  return (
    <>
      <Card
        title="异常工单列表"
        style={{ minHeight: height }}
        className="cute"
        // extra={<Button type="primary">导出</Button>}
      >
        <Form className="flow fix-label padding-bottom">
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item label="系统来源">
                {getFieldDecorator('sourceFrom')(
                  <Select allowClear placeholder="请选择">
                    {sourceFromMap.map(item => {
                      return (
                        <Select.Option value={item.attrValue}>{item.attrValueName}</Select.Option>
                      );
                    })}
                  </Select>
                )}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="异常分类">
                {getFieldDecorator('exceptionType')(
                  <Select allowClear placeholder="请选择">
                    {exceptionTypeMap.map(item => {
                      return (
                        <Select.Option value={item.attrValue}>{item.attrValueName}</Select.Option>
                      );
                    })}
                  </Select>
                )}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="异常名称">
                {getFieldDecorator('exceptionModelName')(<Input allowClear placeholder="请输入" />)}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="异常编码">
                {getFieldDecorator('exceptionCode')(<Input allowClear placeholder="请输入" />)}
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item label="异常处理状态">
                {getFieldDecorator('exceptionStatus')(
                  <Select allowClear placeholder="请选择">
                    {exceptionStatusMap.map(item => {
                      return (
                        <Select.Option value={item.attrValue}>{item.attrValueName}</Select.Option>
                      );
                    })}
                  </Select>
                )}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="流程实例标识">
                {getFieldDecorator('flowInstId')(<Input allowClear placeholder="请输入" />)}
              </Form.Item>
            </Col>
            <Col span={12} className="text-right">
              <Button type="primary" onClick={submit}>
                查询
              </Button>
              <Button className="margin-left" onClick={handleReset}>
                重置
              </Button>
            </Col>
          </Row>
        </Form>
        <SlickTable
          style={{ marginTop: 8 }}
          rowKey={record => record.exceptionInstId}
          columns={columns}
          {...restTableProps}
          data={{
            pagination: {
              ...pagination,
              pageSize: size,
            },
          }}
          pick="checkbox"
          extra={
            selectedRows.length > 0 ? (
              <Button type="primary" ghost onClick={handleBatch}>
                批量处理
              </Button>
            ) : null
          }
          onSelectRow={handleSelectRows}
          selectedRows={selectedRows}
        />
      </Card>
      <Drawer
        title="异常单详情"
        destroyOnClose
        width={620}
        onClose={onClose}
        visible={visible}
        bodyStyle={{ paddingBottom: 80 }}
      >
        <Operpage close={onClose} refresh={refresh} />
      </Drawer>

      {dealvisible ? <Deal close={dealClose} visible={dealvisible} onConfirm={onConfirm} /> : null}
    </>
  );
}

export default connect(({ setting }) => ({
  size: setting.size,
}))(Form.create()(AbnormalOrder));
